<template>
  <div class="app-container">
    <!--<el-tabs v-model="activeTab" >-->
    <!--<el-tab-pane v-for="item in tabOptions" :key="item.key" :label="item.value" :name="item.key"></el-tab-pane>-->
    <!--</el-tabs>-->

    <el-form
      :model="postForm"
      v-loading="formLoading"
      :rules="rules"
      ref="postForm"
      label-width="220px"
      label-position="right"
    >
      <div class="font-family-h font-bold margin-t50 margin-b40">
        <i class="square"></i>基本信息
      </div>
      <div v-show="isEdit" style="text-align:right;margin-right:20px;">
        <el-button type="primary" icon="el-icon-edit" @click="linkToCreate">{{ createText }}</el-button>
      </div>
      <el-form-item label="课程名称：" prop="name">
        <el-input
          :maxlength="80"
          v-model="postForm.name"
          placeholder="建议字数在15字以内，最多不超过40字"
          style="width: 420px"
        ></el-input>
      </el-form-item>
      <el-form-item label="课程简介：" prop="intro">
        <el-input
          :maxlength="80"
          v-model="postForm.intro"
          placeholder="建议字数在15字以内，最多不超过40字"
          style="width: 420px"
        ></el-input>
      </el-form-item>
      <el-row style="width: 760px">
        <el-col :span="8">
          <el-form-item label="选择讲师：">
            <multiselect
              style="width:420px;"
              v-model="lecturerInfo"
              :options="lecturerList"
              track-by="lecturerId"
              label="name"
              placeholder="搜索讲师"
              selectLabel="选择"
              deselectLabel="删除"
              @search-change="syncSearchLecturers"
              @select="lecturerOptionSelect"
              @remove="lecturerOptionRemove"
              :internalSearch="false"
            >
              <span slot="noResult">无结果</span>
            </multiselect>
          </el-form-item>
        </el-col>
        <span style="float:right">
          <el-button class="el-btn" @click="linkToLecturer">添加讲师</el-button>
        </span>
      </el-row>
      <!-- <el-form-item label="课程图片(宽180*高120)：" prop="courseAvatar">
        <div class="clearfix">
          <img class="fl margin-r" :src="postForm.courseAvatar" @error="setDefultImg" width="180" height="120" alt="">
          <el-upload
            class="fl"
            ref="avatarUpload"
            name="avatar"
            :action="imageUploadUrl"
            list-type="picture"
            :before-upload="handleBeforeUpload"
            :on-success="handleAvatarSuccess"
            :show-file-list="false"
            :auto-upload="true"
            style="width: 420px">
            <el-button slot="trigger" size="small"  class="el-btn">选取文件</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过3m</div>
          </el-upload>
        </div>
      </el-form-item>-->
      <el-form-item label="课程轮播(宽200*高200)：">
        <div class="clearfix">
          <el-upload
            :action="imageUploadUrl"
            list-type="picture-card"
            name="avatar"
            :file-list="postForm.banner"
            :limit="5"
            :before-upload="handleBeforeUpload"
            :on-success="handleBannerSuccess"
            :on-remove="handleRemove"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <div class="el-upload__tip" slot="tip">只能上传图片文件，且不超过3MB（第一张作为缩略图）</div>
        </div>
      </el-form-item>
      <el-form-item label="课程视频(MP4格式)：" prop="courseVideo">
        <el-upload
          class="upload-demo"
          name="file"
          :action="videoUploadUrl"
          :show-file-list="false"
          :data="formData"
          :before-upload="beforeVideoUpload"
          :on-success="handleVideoSuccess"
          :on-progress="uploadVideoProcess"
          drag
        >
          <video
            v-if="postForm.courseVideo && !videoFlag"
            controls="controls"
            style="width:100%;height:100%;"
          >
            <source :src="postForm.courseVideo" type="video/mp4" />您的浏览器不支持视频播放。
          </video>
          <el-progress
            v-if="videoFlag"
            type="circle"
            :percentage="videoUploadPercent"
            style="margin-top:1.9rem"
          ></el-progress>
          <template v-else>
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将视频拖到此处，或
              <em>点击上传</em>
            </div>
            <div class="el-upload__tip" slot="tip">只能上传MP4/文件，且不超过100MB（点击视频画面处可更换视频）</div>
          </template>
        </el-upload>
      </el-form-item>
      <!-- <el-form-item label="课程图片(宽180*高120)：" prop="courseAvatar">
        <image-component class="fl" :image="postForm.courseAvatar" :width="'180px'" :height="'120px'"></image-component>
        <el-button  class="fl el-btn" size="small" icon="upload" style="bottom: 15px;margin-left: 40px;" @click="imagecropperShow=true">
          更换图片
        </el-button>
        <image-cropper :width="360" :height="240" :url="imageUploadUrl" @close='closeImageCropper'
                      @crop-upload-success="cropSuccess" langType="zh"
                      :key="imagecropperKey" v-show="imagecropperShow"></image-cropper>
      </el-form-item>-->
      <el-form-item label="课程类型：" v-show="courseTypeShow">
        <el-select v-model.number="postForm.courseType" style="width: 420px">
          <el-option
            v-for="item in courseTypeOptions"
            :key="item.key"
            :label="item.value"
            :value="item.key"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-row style="width: 760px">
        <el-col :span="7" v-if="!postForm.columnId">
          <el-form-item label="课程分类：" v-show="categoryShow">
            <el-select
              v-model.number="postForm.parentCatId"
              clearable
              placeholder="请选择一级分类"
              style="width: 200px"
              @change="parentSelect"
            >
              <el-option
                v-for="item in parentCategoryOptions"
                :key="item.catId"
                :label="item.name"
                :value="item.catId"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="!postForm.columnId">
          <el-form-item v-show="categoryShow">
            <el-select
              v-model.number="postForm.childCatId"
              clearable
              placeholder="请选择二级分类"
              style="width: 200px"
            >
              <el-option
                v-for="item in childCategoryOptions"
                :key="item.catId"
                :label="item.name"
                :value="item.catId"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <span style="float:right">
          <el-button @click="linkToCategory" class="el-btn" v-if="!postForm.columnId">添加分类</el-button>
        </span>
      </el-row>
      <el-form-item label="适应人群：" prop="suitable">
        <el-input
          :maxlength="60"
          v-model="postForm.suitable"
          placeholder="适应人群，课程详情下显示"
          style="width: 600px"
        ></el-input>
      </el-form-item>
      <el-form-item label="观看权限：" prop="permission" v-show="permitShow" v-if="!postForm.columnId">
        <el-select
          v-model.number="postForm.permission"
          placeholder="请选择观看权限"
          style="width: 420px"
          @change="permitSelect"
        >
          <el-option
            v-for="(key, value) in coursePermitOptions"
            :key="key"
            :label="value"
            :value="key"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="课程价格（元）：" prop="price" v-show="priceShow" v-if="!postForm.columnId">
        <el-input
          type="number"
          v-model.number="postForm.price"
          min="0"
          style="width: 420px"
          placeholder="请输入课程价格"
        ></el-input>
      </el-form-item>
      <el-form-item
        label="积分可抵扣金额（元）："
        prop="deductibleAmount"
        v-show="creditShow"
        v-if="!postForm.columnId"
      >
        <el-input
          type="number"
          v-model.number="postForm.deductibleAmount"
          min="0"
          style="width: 420px"
        ></el-input>
        <span class="el-form-tip">（购买时允许积分抵扣的金额）</span>
      </el-form-item>
      <el-form-item label="课程详情：" v-show="descShow" prop="desc">
        <tinymce :height="300" v-model="postForm.desc" style="width: 705px;"></tinymce>
      </el-form-item>
      <el-form-item label="栏目排序：" prop="sort" v-if="this.$route.query.columnId">
        <el-input type="number" v-model.number="postForm.sortIncolumn" style="width: 420px"></el-input>
        <span class="el-form-tip">（课程在栏目详情中的排序，数值越大排序越前）</span>
      </el-form-item>
      <el-form-item label="课程排序：" prop="sort" v-show="sortShow" v-if="!postForm.columnId">
        <el-input type="number" v-model.number="postForm.sort" min="0" style="width: 420px"></el-input>
        <span class="el-form-tip">（在课程列表中的排序，数值越大排序越前）</span>
      </el-form-item>

      <!-- <el-form-item label="预告二维码(宽640*高1280):" v-show="liveShow" prop="forenoticeQrcodeBg">
          <el-upload
            ref="previewUpload"
            name="avatar"
            :action="imageUploadUrl"
            list-type="picture"
            :before-upload="handleBeforeUpload"
            :on-success="handlePreviewSuccess"
            :on-remove="handlePreviewRemove"
            :on-change="handleFileChange"
            :file-list="previewList"
            :limit="1"
            :auto-upload="false"
            style="width: 420px">
            <el-button class="el-btn" slot="trigger" size="small" @click="beforeChooseQr">选取文件</el-button>
            <el-button class="el-btn" style="margin-left: 10px;" size="small" @click="submitPreviewUpload">立即上传</el-button>
          </el-upload>
          <el-upload
            class="preview-uploader fl" name="avatar"
            :action="imageUploadUrl"
            :show-file-list="false"
            :on-success="handlePreviewSuccess"
            :before-upload="handleBeforeUpload">
            <img v-if="postForm.forenoticeQrcodeBg" :src="postForm.forenoticeQrcodeBg" class="preview">
            <i v-else class="el-icon-plus preview-uploader-icon"></i>
          </el-upload>
          <span class="el-form-tip fl">（点击图片更改）</span>
      </el-form-item>-->
      <el-form-item label="预告二维码(宽640*高1280)：" v-if="liveShow" prop="forenoticeQrcodeBg">
        <div class="clearfix">
          <img
            class="fl margin-r"
            :src="postForm.forenoticeQrcodeBg"
            @error="setDefultImg"
            width="180"
            height="320"
            alt
          />
          <el-upload
            class="fl"
            ref="previewUpload"
            name="avatar"
            :action="imageUploadUrl"
            list-type="picture"
            :before-upload="handleBeforeUpload"
            :on-success="handlePreviewSuccess"
            :show-file-list="false"
            :auto-upload="true"
            style="width: 420px"
          >
            <el-button slot="trigger" size="small" class="el-btn">选取文件</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过3m</div>
          </el-upload>
        </div>
      </el-form-item>
      <el-form-item label="试看图文：" v-show="previewShow">
        <tinymce :height="300" v-model="postForm.previewText" style="width: 705px;"></tinymce>
      </el-form-item>
      <el-form-item label="详细图文：" v-if="previewShow" prop="detail">
        <tinymce :height="300" v-model="postForm.detail" style="width: 705px;"></tinymce>
      </el-form-item>
      <div class="font-family-h font-bold margin-t50 margin-b40">
        <i class="square"></i>推荐设置
      </div>
      <!--<el-form-item label="是否开通邀请卡：" prop="isInvitionCard" v-if="!postForm.columnId">-->
      <!--<el-select v-model.number="postForm.isInvitionCard" style="width: 420px" @change="inviteSelect">-->
      <!--<el-option v-for="item in commonOptions" :key="item.key" :label="item.value" :value="item.key"></el-option>-->
      <!--</el-select>-->
      <!--</el-form-item>-->
      <el-form-item label="邀请卡:" prop="isInvitionCard" v-if="!postForm.columnId">
        <el-radio-group v-model.number="postForm.isInvitionCard">
          <el-radio :label="0">关闭</el-radio>
          <el-radio :label="1">开通</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        label="邀请后可优惠："
        prop="deductibleAfterInvition"
        v-show="postForm.isInvitionCard==1"
        v-if="!postForm.columnId"
      >
        <el-input
          type="number"
          v-model.number="postForm.deductibleAfterInvition"
          style="width: 420px"
        ></el-input>元
        <span class="el-form-tip">（邀请优惠和积分抵扣不会同时享受）</span>
      </el-form-item>
      <!-- <el-form-item label="是否热门:" prop="isHot" v-show="hotShow" v-if="!postForm.columnId">
        <el-radio-group v-model.number="postForm.isHot">
          <el-radio :label="0">否</el-radio>
          <el-radio :label="1">是</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="是否预告:" prop="isLive" v-if="!postForm.columnId">
        <el-radio-group v-model.number="isLive" @change="liveSelect">
          <el-radio :label="0">否</el-radio>
          <el-radio :label="1">是</el-radio>
        </el-radio-group>
      </el-form-item>-->
      <!-- <el-form-item label="预告时间：" v-if="isLive" prop="liveAt">
        <el-date-picker
          type="datetime"
          format="yyyy-MM-dd HH:mm:ss"
          placeholder="请输入预告时间"
          v-model="postForm.liveAt"
          @change="timeCheck"
          :picker-options="pickerOptions"
          style="width:420px"
        ></el-date-picker>
      </el-form-item>-->
      <el-form-item label="默认播放次数：" prop="virtualPlays">
        <el-input
          v-model.number="postForm.virtualPlays"
          min="0"
          placeholder="请输入内容"
          style="width: 420px"
        ></el-input>
        <span class="el-form-tip">（前端看到的起始播放次数，请设置合理）</span>
      </el-form-item>
      <el-form-item label="实际播放次数：">
        <el-input v-model="postForm.plays" disabled="disabled" style="width: 420px;"></el-input>
      </el-form-item>
      <!--<el-form-item label="点赞数：">-->
      <!--<el-input v-model.number="postForm.likes" placeholder="请输入内容" style="width: 420px" disabled></el-input>-->
      <!--</el-form-item>-->
      <!--<el-form-item label="分享公众号标题设置：" prop="shareTitle">-->
      <!--<el-input v-model="postForm.shareTitle" placeholder="用于客户分享公众号给微信号有名片的展示" style="width: 600px"></el-input>-->
      <!--</el-form-item>-->
      <el-form-item v-if="!isColumnDetail" label="分享公众号描述：" prop="shareDesc">
        <el-input
          :maxlength="29"
          v-model="postForm.shareDesc"
          placeholder="分享描述，不超过29个字"
          style="width: 600px"
        ></el-input>
      </el-form-item>
      <div class="font-family-h font-bold margin-t50 margin-b40">
        <i class="square"></i>关联设置
      </div>
      <el-form-item label="关联资料">
        <el-table
          v-show="postForm.datumArr.length > 0"
          :data="postForm.datumArr"
          class="c-width40"
          :show-header="true"
          size="mini"
          :border="true"
          style="width:600px;"
        >
          <el-table-column label="资料名称" align="center">
            <template slot-scope="scope">
              <div slot="reference" class="name-wrapper">
                <el-tag size="medium">{{ scope.row.name }}</el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-button size="mini" type="danger" @click="cancelRel(1, scope.$index)">取消关联</el-button>
            </template>
          </el-table-column>
          <el-table-column label="是否允许下载" align="center">
            <template slot-scope="scope">
              <el-radio-group v-model="scope.row.downloadstatus">
                <el-radio :label="0">否</el-radio>
                <el-radio :label="1">是</el-radio>
              </el-radio-group>
            </template>
          </el-table-column>
          <el-table-column label="是否允试看" align="center">
            <template slot-scope="scope">
              <el-radio-group v-model="scope.row.lookstatus">
                <el-radio :label="0">否</el-radio>
                <el-radio :label="1">是</el-radio>
              </el-radio-group>
              <br />
              <span v-if="scope.row.lookstatus > 0">
                试看
                <el-input style="width:60%" v-model="scope.row.lookstatus" placeholder="1"></el-input>页
              </span>
            </template>
          </el-table-column>
        </el-table>
        <el-button
          :disabled="postForm.datumArr.length==100"
          @click="addRelObj(1,postForm.datumArr)"
        >添加资料</el-button>
        <span class="margin-l10 fc">最多可添加100个</span>
      </el-form-item>
      <el-form-item label="关联社群" v-show="socialShow&&!isColumnDetail">
        <el-table
          v-show="postForm.socialArr.length > 0"
          :data="postForm.socialArr"
          style="width:70%"
          :show-header="false"
          size="mini"
          :border="true"
        >
          <el-table-column label="社群名称">
            <template slot-scope="scope">
              <div slot="reference" class="name-wrapper">
                <el-tag size="medium">{{ scope.row.name }}</el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-button size="mini" type="danger" @click="cancelRel(2, scope.$index)">取消关联</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button
          :disabled="postForm.socialArr.length==5"
          @click="addRelObj(2,postForm.socialArr)"
        >添加社群</el-button>
        <span class="margin-l10 fc">最多可添加5个</span>
      </el-form-item>
      <el-form-item label="关联测评" v-show="examShow&&!isColumnDetail">
        <el-table
          v-show="postForm.examArr.length > 0"
          :data="postForm.examArr"
          class="c-width40"
          :show-header="false"
          size="mini"
          :border="true"
        >
          <el-table-column label="测评名称">
            <template slot-scope="scope">
              <div slot="reference" class="name-wrapper">
                <el-tag size="medium">{{ scope.row.name }}</el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-button size="mini" type="danger" @click="cancelRel(3, scope.$index)">取消关联</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button
          :disabled="postForm.examArr.length==5"
          @click="addRelObj(3,postForm.examArr)"
        >添加测评</el-button>
        <span class="margin-l10 fc">最多可添加5个</span>
      </el-form-item>

      <addRelated
        v-if="isShowAddRelated"
        :columnId="postForm.columnId"
        :relType="relType"
        :objData="objData"
        @saveRelated="saveRelated"
        @hideAddRelated="hideAddRelated"
      ></addRelated>

      <!-- <div v-if="!isColumnDetail" class="font-family-h font-bold margin-t50 margin-b40">
        <i class="square"></i>抽成设置
      </div>-->
      <!--<code>-->
      <!--<svg-icon icon-class="message" style="margin-right:10px;color:red;font-size:20px;"></svg-icon>-->
      <!--备注： 以下六个抽成比例之和，不能超过100%；如果还有收益人抽成，则包括收益人的抽成之和不能超过100%-->
      <!--</code>-->
      <!-- <el-form-item v-if="!isColumnDetail" label="是否关联收益人:" prop="isTeacher">
        <el-radio-group v-model.number="postForm.isTeacher">
          <el-radio :label="0">否</el-radio>
          <el-radio :label="1">是</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="选择收益人：" v-show="postForm.isTeacher">
        <multiselect
          style="width:420px;"
          v-model="teacherInfo"
          :options="teacherList"
          track-by="userId"
          label="nickname"
          placeholder="搜索收益人"
          selectLabel="选择"
          deselectLabel="删除"
          @search-change="syncSearchTeachers"
          @select="teacherOptionSelect"
          @remove="teacherOptionRemove"
          :loading="syncLoading"
          :internal-search="false"
        >
          <span slot="noResult">无结果</span>
        </multiselect>
      </el-form-item>
      <el-form-item label="收益人抽成比例(单位%)：" prop="teacherCommissionRate" v-show="postForm.isTeacher">
        <el-input
          type="number"
          min="0"
          max="100"
          v-model.number="postForm.teacherCommissionRate"
          placeholder="请输入讲师抽成比例"
          style="width: 420px"
        ></el-input>
      </el-form-item>-->
      <!--<el-form-item label="是否单独设置课程抽成比例：">-->
      <!--<el-select v-model.number="postForm.isCourseCommission" placeholder="请选择" style="width: 420px" @change="courseCommissionSelect">-->
      <!--<el-option v-for="item in commonOptions" :key="item.key" :label="item.value" :value="item.key"></el-option>-->
      <!--</el-select>-->
      <!--</el-form-item>-->
      <!-- <el-form-item v-if="!isColumnDetail" label="是否单独设置课程抽成比例:" prop="isCourseCommission">
        <el-radio-group v-model.number="postForm.isCourseCommission">
          <el-radio :label="0">否</el-radio>
          <el-radio :label="1">是</el-radio>
        </el-radio-group>
      </el-form-item>
      <div v-show="postForm.isCourseCommission&&!isColumnDetail">
        <el-form-item label="分销抽成(单位%)：">
          <el-table :data="levelRateData" border style="width: 100%">
            <el-table-column label="第一级抽成比例">
              <template slot-scope="scope">
                <el-form-item prop="firstCommissionRate">
                  <el-input
                    style="width: 265px"
                    type="number"
                    min="0"
                    max="100"
                    v-model.number="scope.row.firstCommissionRate"
                    placeholder="请输入第一级抽成比例"
                  ></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="第二级抽成比例">
              <template slot-scope="scope">
                <el-form-item prop="secondCommissionRate">
                  <el-input
                    style="width: 265px"
                    type="number"
                    min="0"
                    max="100"
                    v-model.number="scope.row.secondCommissionRate"
                    placeholder="请输入第二级抽成比例"
                  ></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="第三级抽成比例">
              <template slot-scope="scope">
                <el-form-item prop="thirdCommissionRate">
                  <el-input
                    style="width: 265px"
                    type="number"
                    min="0"
                    max="100"
                    v-model.number="scope.row.thirdCommissionRate"
                    placeholder="请输入第三级抽成比例"
                  ></el-input>
                </el-form-item>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="服务商抽成比例(单位%)：" v-if="this.agentLevel > 0">
          <el-table :data="serverRateData" border style="width: 100%">
            <el-table-column label="代理商抽成比例">
              <template slot-scope="scope">
                <el-form-item prop="agentCommissionRate">
                  <el-input
                    style="width: 265px"
                    type="number"
                    min="0"
                    max="100"
                    v-model.number="scope.row.agentCommissionRate"
                    placeholder="请输入代理商抽成比例"
                  ></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="合伙人抽成比例" v-if="this.agentLevel == 3">
              <template slot-scope="scope">
                <el-form-item prop="partnerCommissionRate">
                  <el-input
                    style="width: 265px"
                    type="number"
                    min="0"
                    max="100"
                    v-model.number="scope.row.partnerCommissionRate"
                    placeholder="请输入合伙人抽成比例"
                  ></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="分公司抽成比例" v-if="this.agentLevel ==3">
              <template slot-scope="scope">
                <el-form-item prop="branchCommissionRate">
                  <el-input
                    style="width: 265px"
                    type="number"
                    min="0"
                    max="100"
                    v-model.number="scope.row.branchCommissionRate"
                    placeholder="请输入分公司抽成比例"
                  ></el-input>
                </el-form-item>
              </template>
            </el-table-column>
          </el-table>
      </el-form-item>-->
      <!-- </div> -->
      <div
        class="font-family-h font-bold margin-t50 margin-b40"
        v-if="postForm.courseType == 0 || postForm.courseType == 1"
      >
        <i class="square"></i>收费课程试看设置
      </div>
      <el-form-item label="是否免费观看第一节:" v-if="postForm.courseType == 0">
        <el-radio-group v-model.number="postForm.allowWholeWatch">
          <el-radio :label="0">否</el-radio>
          <el-radio :label="1">是</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        :label="postForm.courseType == 0 ? '是否试看第一节:' : '是否试听音频:'"
        v-show="postForm.allowWholeWatch == 0 || postForm.courseType == 1"
      >
        <el-radio-group v-model.number="postForm.watchPermission">
          <el-radio :label="0">否</el-radio>
          <el-radio :label="1">是</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        :label="postForm.courseType == 0 ? '第一节试看时长(分钟):' : '第一节试听时长(分钟):'"
        prop="teacherCommissionRate"
        v-show="postForm.watchPermission == 1 && (postForm.allowWholeWatch == 0 || postForm.courseType == 1)"
      >
        <el-input
          type="number"
          min="0"
          max="100"
          v-model.number="postForm.watchTime"
          placeholder="请输入试看时长"
          style="width: 420px"
        ></el-input>
      </el-form-item>
      <div class="font-family-h font-bold margin-t50 margin-b40">
        <i class="square"></i>上架设置
      </div>
      <el-form-item label="是否上架:">
        <el-radio-group v-model.number="postForm.status">
          <el-radio :label="2">暂不上架</el-radio>
          <el-radio :label="1">立即上架</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label-width="320px">
        <el-button
          type="primary"
          v-loading.fullscreen="btnLoading"
          icon="el-icon-check"
          @click="submitForm"
        >保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { getQiniuToken } from "@/api/qiniu";
import { delImg } from "@/api/common";
import Tinymce from "@/components/Tinymce";
import Multiselect from "vue-multiselect"; // 引入 vue-multiselect 组件
import "vue-multiselect/dist/vue-multiselect.min.css";
import addRelated from "@/views/courseColumn/components/addRelated.vue"; // 引入关联组件
import {
  getPermissionOptions,
  getCourse,
  createCourse,
  updateCourse
} from "@/api/course";
import { getParentCategories, getChildCategories } from "@/api/courseCategory";
import { getLecturerSearch, getLecturerList } from "@/api/lecturer";
import { getMemberSearch, initMemberList } from "@/api/member";
import {
  enablePointModule,
  enableDatumModule,
  enableSocialModule,
  enableExamModule,
  getAgentLevels
} from "@/utils/permission";
import { getChineseStrLength } from "@/utils/validate";
import defultImg from "@/assets/defult270.png";
// import imageComponent from '@/components/imageComponent'
// import ImageCropper from '@/components/ImageCropper'

var postForm = {
  datumsStatus: "",
  columnId: 0,
  sortIncolumn: 0,
  name: "",
  suitable: "",
  courseType: null,
  parentCatId: null,
  childCatId: null,
  lecturerId: null,
  permission: null,
  price: 0,
  tryRead: "",
  isInvitionCard: 1,
  deductibleAfterInvition: 0,
  deductibleAmount: 0,
  sort: 0,
  isHot: 0,
  status: 1,
  liveAt: null,
  virtualPlays: 0,
  likes: 0,
  courseAvatar: "",
  forenoticeQrcodeBg: null,
  desc: null,
  detail: null,
  previewText: null,
  isTeacher: 0,
  teacherId: null,
  teacherCommissionRate: 0,
  isCourseCommission: 0,
  firstCommissionRate: 0,
  secondCommissionRate: 0,
  thirdCommissionRate: 0,
  agentCommissionRate: 0,
  partnerCommissionRate: 0,
  branchCommissionRate: 0,
  shareTitle: null,
  shareDesc: null,
  datumArr: [],
  socialArr: [],
  examArr: [],
  banner: [],
  allowWholeWatch: 0,
  watchPermission: 0,
  watchTime: 0
};

const statusOptions = [{ key: 1, value: "是" }, { key: -2, value: "否" }];

const commonOptions = [{ key: 1, value: "是" }, { key: 0, value: "否" }];

const tabOptions = [
  { key: "basic", value: "基本信息" },
  { key: "associate", value: "关联设置" },
  { key: "share", value: "分享设置" },
  { key: "commission", value: "抽成设置" }
];

const courseTypeOptions = [
  { key: 0, value: "视频" },
  { key: 1, value: "音频" },
  { key: 2, value: "图文" }
];

const levelRateData = [
  {
    firstCommissionRate: null,
    secondCommissionRate: null,
    thirdCommissionRate: null
  }
];
const serverRateData = [
  {
    agentCommissionRate: null,
    partnerCommissionRate: null,
    branchCommissionRate: null
  }
];

export default {
  components: { Tinymce, Multiselect, addRelated },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    const validatePrice = (rule, value, callback) => {
      if (this.postForm.permission != 19) {
        if (!value) {
          callback(new Error("请输入课程价格"));
        } else {
          if (value < 0) {
            callback("价格不能小于0");
          } else {
            callback();
          }
        }
      } else {
        callback();
      }
    };
    const validateDeductibleAfterInvition = (rule, value, callback) => {
      if (value && value < 0) {
        callback("请输入正确的数值");
      } else {
        if (
          this.postForm.permission != 19 &&
          parseFloat(value) > parseFloat(this.postForm.price)
        ) {
          callback("邀请优惠金额不能超过课程价格");
        }

        callback();
      }
    };
    const validateNumber = (rule, value, callback) => {
      if (value && isNaN(value)) {
        callback("请输入正确的数值");
      } else {
        if (value < 0) {
          callback("请输入正确的数值");
        }
        callback();
      }
    };
    const validateDeductibleAmount = (rule, value, callback) => {
      if (value && value < 0) {
        callback("积分可以抵扣金额不能小于0");
      } else {
        if (
          this.postForm.permission != 19 &&
          parseFloat(value) > parseFloat(this.postForm.price)
        ) {
          console.log(value, this.postForm.price);
          callback("积分抵扣金额不能超过课程价格");
        }

        callback();
      }
    };

    return {
      isColumnDetail: false,
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 24 * 60 * 60 * 1000;
        }
      },
      isLive: 0,
      postForm: Object.assign({}, postForm),
      formData: {
        token: null
        // key: null
      },
      rules: {
        name: [{ required: true, message: "请输入课程名称", trigger: "blur" }],
        intro: [{ required: true, message: "请输入课程简介", trigger: "blur" }],
        //courseAvatar: [{ required: true, message: '请选择图片', trigger: 'change' }],
        //courseVideo: [{ required: true, message: '请上传详情视频', trigger: 'change' }],
        desc: [
          { required: true, message: "请上填写课程详情", trigger: "blur" }
        ],
        suitable: [
          { required: true, message: "请上填写事宜人群", trigger: "blur" }
        ],
        forenoticeQrcodeBg: [
          { required: true, message: "请选择预告二维码图片", trigger: "change" }
        ],
        permission: [
          { required: true, message: "请选择观看权限", trigger: "change" }
        ],
        price: [{ required: true, trigger: "blur", validator: validatePrice }],
        detail: [
          { required: true, message: "请输入图文详情", trigger: "blur" }
        ],
        // price: [{ required: true, trigger: 'blur', validator: validatePrice }],
        isInvitionCard: [
          { required: true, message: "请选择是否开通邀请卡", trigger: "change" }
        ],
        // liveAt: [
        //   { required: true, message: "请选择预告时间", trigger: "change" }
        // ],
        deductibleAfterInvition: [
          { validator: validateDeductibleAfterInvition, trigger: "blur" }
        ],
        deductibleAmount: [
          { validator: validateDeductibleAmount, trigger: "blur" }
        ],
        sort: [{ validator: validateNumber, trigger: "blur" }],
        virtualPlays: [{ validator: validateNumber, trigger: "blur" }],
        teacherCommissionRate: [
          { max: 100, min: 0, validator: validateNumber, trigger: "submitForm" }
        ],
        firstCommissionRate: [
          { max: 100, min: 0, validator: validateNumber, trigger: "submitForm" }
        ],
        secondCommissionRate: [
          { max: 100, min: 0, validator: validateNumber, trigger: "submitForm" }
        ],
        thirdCommissionRate: [
          { max: 100, min: 0, validator: validateNumber, trigger: "submitForm" }
        ],
        agentCommissionRate: [
          { max: 100, min: 0, validator: validateNumber, trigger: "submitForm" }
        ],
        partnerCommissionRate: [
          { max: 100, min: 0, validator: validateNumber, trigger: "submitForm" }
        ],
        branchCommissionRate: [
          { max: 100, min: 0, validator: validateNumber, trigger: "submitForm" }
        ]
      },
      formLoading: false,
      btnLoading: false,
      parentCategoryOptions: [],
      childCategoryOptions: [],
      coursePermitOptions: [],
      courseTypeOptions,
      statusOptions,
      commonOptions,
      categoryShow: true,
      permitShow: true,
      columnShow: false,
      priceShow: true,
      inviteShow: true,
      creditShow: true,
      sortShow: true,
      liveShow: false,
      hotShow: true,
      pulloffShow: true,
      descShow: true,
      previewShow: false,
      lecturerInfo: [],
      lecturerList: [],
      avatarList: [],
      previewList: [],
      tabOptions,
      activeTab: "basic",
      teacherInfo: [],
      teacherList: [],
      inviteDisabled: false,
      courseTypeShow: false,
      levelRateData,
      serverRateData,
      isShowAddRelated: false,
      relType: null,
      objData: [],
      encodeUserId: null,
      agentLevel: 0,
      datumShow: true,
      socialShow: true,
      examShow: true,
      createText: null,
      syncLoading: false,
      imageUploadUrl: process.env.BASE_API + "/common/course/imageUpload",
      videoUploadUrl: "http://upload-z2.qiniup.com",
      baseUrl: "",
      videoFlag: false,
      videoUploadPercent: 0.0
      // imagecropperShow: false,
      // imagecropperKey: 0
    };
  },
  mounted() {
    this.postForm.banner = [];
  },
  created() {
    this.getToken();
    this.postForm.banner = [];
    this.initOption();
    this.initData();
    this.enableModules();
    if (this.$route.params.columnId == -1) {
      this.isColumnDetail = false;
    } else {
      this.isColumnDetail = true;
    }
  },
  watch: {
    $route: function(to, from) {
      console.log("路由", this.$route);
      if (to.name == "editCourse") {
        this.initData();
      }
      if (this.$route.params.columnId == -1) {
        this.isColumnDetail = false;
      } else {
        this.isColumnDetail = true;
      }
    },
    postForm: {
      handler(val) {
        if (val.allowWholeWatch == 1) {
          this.postForm.watchPermission = 0;
          this.postForm.watchTime = 0;
        }
      },
      deep: true
    }
  },
  methods: {
    getToken() {
      getQiniuToken()
        .then(res => {
          this.formData.token = res.data.data.token;
          this.baseUrl = res.data.data.baseUrl;
        })
        .catch(err => {
          console.log(err);
        });
    },
    enableModules() {
      if (!enablePointModule()) {
        this.creditShow = false;
      }
      if (!enableDatumModule()) {
        this.datumShow = false;
      }
      if (!enableSocialModule()) {
        this.socialShow = false;
      }
      if (!enableExamModule()) {
        this.examShow = false;
      }
      if (!enablePointModule() && !enableDatumModule() && !enableExamModule()) {
        this.tabOptions = this.tabOptions.filter(item => {
          return item.key != "associate";
        });
      }
      this.agentLevel = getAgentLevels();
    },
    initOption() {
      getParentCategories()
        .then(res => {
          this.parentCategoryOptions = res.data.data;
        })
        .catch(err => {
          console.log(err);
        });

      getPermissionOptions()
        .then(res => {
          this.coursePermitOptions = res.data.data;
        })
        .catch(err => {
          console.log(err);
        });

      getLecturerList()
        .then(res => {
          const resData = res.data.data.data;
          this.lecturerList = [];
          for (let i = 0; i < resData.length; i++) {
            this.lecturerList.push({
              lecturerId: resData[i].lecturerId,
              name: resData[i].name + `（ID: ${resData[i].lecturerId}）`
            });
          }
        })
        .catch(err => {
          console.log(err);
        });

      initMemberList()
        .then(res => {
          const resData = res.data.data;
          this.teacherList = [];
          for (let i = 0; i < resData.length; i++) {
            this.teacherList.push({
              userId: resData[i].userId,
              nickname:
                resData[i].nickname + `（ID: ${resData[i].encodeUserId}）`
            });
          }
        })
        .catch(err => {
          console.log(err);
        });

      const type = this.$route.params.courseType;
      let courseType = "";
      this.createText = "新建相似课程";
      switch (type) {
        case "videos":
          courseType = 0;
          this.createText = "新建相似视频";
          break;
        case "audios":
          courseType = 1;
          this.createText = "新建相似音频";
          break;
        case "articles":
          courseType = 2;
          //this.descShow = false
          this.previewShow = true;
          this.createText = "新建相似图文";
          break;
        case "previews":
          courseType = 0;
          this.isLive = 1;
          this.liveShow = true;
          this.courseTypeShow = true;
          break;
      }
      this.postForm.courseType = courseType;
    },
    initData() {
      if (this.isEdit) {
        const courseId = this.$route.params.courseId;
        this.formLoading = true;
        getCourse(courseId)
          .then(res => {
            this.postForm = res.data.data.data;

            // for (const i in this.postForm) {
            //   if (i == 'datumArr') {
            //     for (let j = 0; j < this.postForm[i].length; j++) {
            //       this.postForm[i][j].downloadstatus = 0;
            //       this.postForm[i][j].lookstatus = 0;
            //     }
            //   }
            // }
            // console.log(this.postForm);

            this.encodeUserId = res.data.data.encodeUserId;
            this.handlePostForm();
            this.formLoading = false;
          })
          .catch(err => {
            this.formLoading = false;
            console.log(err);
          });
      } else {
        const postData = this.$route.params.postData;
        if (postData) {
          delete postData.courseId;
          delete postData.columnId;
          this.postForm = postData;
          this.encodeUserId = this.$route.params.encodeUserId;
          this.handlePostForm();
        }
      }
    },
    handlePostForm() {
      if (this.postForm.columnId != 0 && this.postForm.columnId != null) {
        this.tabOptions = [{ key: "basic", value: "基本信息" }];
      }
      if (this.postForm.parentId != 0) {
        this.parentSelect(this.postForm.parentCatId, true);
      }
      if (this.postForm.permission == 19) {
        this.priceShow = false;
        this.creditShow = false;
        this.inviteDisabled = true;
      }
      if (this.postForm.isInvitionCard == 1) {
        this.inviteShow = true;
      }
      if (this.postForm.liveAt != null && this.isLiveTime()) {
        this.isLive = 1;
        this.liveShow = true;
      }
      if (this.postForm.lecturerId != null) {
        getLecturerSearch(this.postForm.lecturerId)
          .then(res => {
            this.lecturerInfo = res.data.data[0];
          })
          .catch(err => {
            console.log(err);
          });
      }
      if (this.postForm.courseType == 2) {
        //this.descShow = false
        this.previewShow = true;
      }
      if (this.postForm.courseAvatar) {
        this.avatarList = [{ url: this.postForm.courseAvatar }];
      }
      if (this.postForm.forenoticeQrcodeBg) {
        this.previewList = [{ url: this.postForm.forenoticeQrcodeBg }];
      }
      if (this.postForm.teacherId != null) {
        getMemberSearch(this.encodeUserId)
          .then(res => {
            const resData = res.data.data[0];
            this.teacherInfo = {
              userId: resData.userId,
              nickname: resData.nickname + `（ID: ${resData.encodeUserId}）`
            };
          })
          .catch(err => {
            console.log(err);
          });
      }
      // 获取分销抽成比例
      this.levelRateData = [
        {
          firstCommissionRate: this.postForm.firstCommissionRate,
          secondCommissionRate: this.postForm.secondCommissionRate,
          thirdCommissionRate: this.postForm.thirdCommissionRate
        }
      ];
      // 获取服务商抽成比例
      this.serverRateData = [
        {
          agentCommissionRate: this.postForm.agentCommissionRate,
          partnerCommissionRate: this.postForm.partnerCommissionRate,
          branchCommissionRate: this.postForm.branchCommissionRate
        }
      ];
    },
    parentSelect(id, isEdit = false) {
      this.childCategoryOptions = [];
      if (!isEdit) {
        this.postForm.childCatId = null;
      }
      if (!id) {
        return false;
      }

      getChildCategories(id)
        .then(res => {
          this.childCategoryOptions = res.data.data;
        })
        .catch(err => {
          console.log(err);
        });
    },
    isLiveTime() {
      const currentTime = Date.parse(new Date());
      const liveTime = Date.parse(new Date(this.postForm.liveAt));
      return liveTime > currentTime;
    },
    permitSelect(val) {
      if (val == 19) {
        this.priceShow = false;
        this.creditShow = false;
        this.inviteDisabled = true;
      } else {
        this.priceShow = true;
        if (enablePointModule()) {
          this.creditShow = true;
        } else {
          this.creditShow = false;
        }
        this.inviteDisabled = false;
      }
    },
    inviteSelect(val) {
      if (val == 0) {
        this.inviteShow = false;
      } else {
        this.inviteShow = true;
      }
    },
    liveSelect(val) {
      if (val == 1) {
        this.liveShow = true;
      } else {
        this.liveShow = false;
      }
      this.postForm.liveAt = null;
    },
    timeCheck(val) {
      const currentTime = Date.parse(new Date());
      if (val < currentTime) {
        this.$message({
          message: "预告时间不能小于当前时间",
          type: "warning"
        });
      }
    },
    syncSearchLecturers(query) {
      this.syncLoading = true;
      getLecturerSearch(query)
        .then(res => {
          this.syncLoading = false;
          const resData = res.data.data;
          this.lecturerList = [];
          for (let i = 0; i < resData.length; i++) {
            this.lecturerList.push({
              lecturerId: resData[i].lecturerId,
              name: resData[i].name + `（ID: ${resData[i].lecturerId}）`
            });
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    lecturerOptionSelect(selectedOption, id) {
      this.postForm.lecturerId = selectedOption.lecturerId;
    },
    lecturerOptionRemove(removedOption, id) {
      this.postForm.lecturerId = null;
    },
    handleCreate() {
      createCourse(this.postForm)
        .then(res => {
          if (res.data.statusCode == 200) {
            this.$notify({
              title: "提示",
              message: "提交成功!",
              type: "success"
            });
            this.btnLoading = false;
            this.close();
          } else {
            this.btnLoading = false;
            this.$notify({
              title: "提示",
              message: "提交失败!",
              type: "error"
            });
          }
        })
        .catch(err => {
          this.btnLoading = false;
          console.log(err);
        });
    },
    handleUpdate() {
      const courseId = this.$route.params.courseId;
      updateCourse(courseId, this.postForm)
        .then(res => {
          if (res.data.statusCode == 200) {
            this.$notify({
              title: "提示",
              message: "提交成功!",
              type: "success"
            });
            this.btnLoading = false;
            this.close();
          } else {
            this.btnLoading = false;
            this.$notify({
              title: "提示",
              message: "提交失败!",
              type: "error"
            });
          }
        })
        .catch(err => {
          this.btnLoading = false;
          console.log(err);
        });
    },
    submitForm() {
      this.postForm.firstCommissionRate = this.levelRateData[0]
        .firstCommissionRate
        ? parseFloat(this.levelRateData[0].firstCommissionRate)
        : 0;
      this.postForm.secondCommissionRate = this.levelRateData[0]
        .secondCommissionRate
        ? parseFloat(this.levelRateData[0].secondCommissionRate)
        : 0;
      this.postForm.thirdCommissionRate = this.levelRateData[0]
        .thirdCommissionRate
        ? parseFloat(this.levelRateData[0].thirdCommissionRate)
        : 0;
      this.postForm.agentCommissionRate = this.serverRateData[0]
        .agentCommissionRate
        ? parseFloat(this.serverRateData[0].agentCommissionRate)
        : 0;
      this.postForm.partnerCommissionRate = this.serverRateData[0]
        .partnerCommissionRate
        ? parseFloat(this.serverRateData[0].partnerCommissionRate)
        : 0;
      this.postForm.branchCommissionRate = this.serverRateData[0]
        .branchCommissionRate
        ? parseFloat(this.serverRateData[0].branchCommissionRate)
        : 0;

      // 从专栏新增课程
      // if (this.$route.params.columnId) {
      //   this.postForm.columnId = this.$route.params.columnId
      // }
      if (!this.postForm.sort) {
        this.postForm.sort = 0;
      }
      if (!this.postForm.virtualPlays) {
        this.postForm.virtualPlays = 0;
      }
      if (parseFloat(this.postForm.virtualPlays) < 0) {
        this.$message({
          message: "播放次数设置不能小于0",
          type: "warning"
        });
        return;
      }

      if (parseFloat(this.postForm.sort) < 0) {
        this.$message({
          message: "排序不能小于0",
          type: "warning"
        });
        return;
      }
      if (
        this.postForm.name == "" ||
        this.postForm.name.trim() == "" ||
        this.postForm.name == null
      ) {
        this.$message({
          message: "课程名称必填",
          type: "warning"
        });
        return;
      }
      if (getChineseStrLength(this.postForm.name) > 80) {
        this.$message({
          message: "课程名称不能超过40个字",
          type: "warning"
        });
        return;
      }

      if (this.postForm.permission == "" || this.postForm.permission == null) {
        this.$message({
          message: "观看权限必填",
          type: "warning"
        });
        return;
      }
      if (
        this.postForm.permission != 19 &&
        (this.postForm.price == "" || this.postForm.price == null)
      ) {
        this.$message({
          message: "观看权限不是免费的时候价格必填",
          type: "warning"
        });
        return;
      }
      /*if (this.postForm.courseAvatar == null || this.postForm.courseAvatar == '') {
          this.$message({
            message: '课程图片必选',
            type: 'warning'
          })
          return
        }*/
      if (this.postForm.banner.length == 0) {
        this.$message({
          message: "至少上传一张轮播图",
          type: "warning"
        });
        return;
      }
      if (
        this.liveShow &&
        (this.postForm.forenoticeQrcodeBg == null ||
          this.postForm.forenoticeQrcodeBg == "")
      ) {
        this.$message({
          message: "二维码背景图必选",
          type: "warning"
        });
        return;
      }
      if (
        this.postForm.permission != 19 &&
        parseFloat(this.postForm.deductibleAmount) >
          parseFloat(this.postForm.price)
      ) {
        this.$message({
          message: "积分可抵扣价格不能大于课程价格",
          type: "warning"
        });
        return;
      }
      if (
        parseFloat(this.postForm.deductibleAmount) < 0 ||
        parseFloat(this.postForm.deductibleAfterInvition) < 0
      ) {
        this.$message({
          message: "积分可抵扣价格跟邀请可优惠价格不能小于0",
          type: "warning"
        });
        return;
      }
      if (this.previewShow && !this.postForm.detail) {
        this.$message({
          message: "图文详情不能为空",
          type: "warning"
        });
        return;
      }
      const type = this.$route.params.courseType;
      if (type == "previews" && !this.postForm.liveAt) {
        this.$message.warning("请输入预告时间");
        return false;
      }
      if (this.isLive == 1) {
        if (this.postForm.liveAt == null || this.postForm.liveAt == "") {
          this.$message.warning("请输入预告时间");
          return;
        }
      }
      if (parseFloat(this.postForm.firstCommissionRate) == 0) {
        if (
          parseFloat(this.postForm.secondCommissionRate) != 0 ||
          parseFloat(this.postForm.thirdCommissionRate) != 0
        ) {
          console.log("二级为0");
          this.$message.warning("课程购买第一级抽成比例为0，第二三级也只能为0");
          return;
        }
      }
      if (parseFloat(this.postForm.secondCommissionRate) == 0) {
        if (parseFloat(this.postForm.thirdCommissionRate) != 0) {
          this.$message.warning("课程购买第二级抽成比例为0，第三级也只能为0");
          return;
        }
      }
      if (!(this.postForm.datumArr == false)) {
        for (let i = 0; i < this.postForm.datumArr.length; i++) {
          const element = this.postForm.datumArr[i];
          if (element.downloadstatus == undefined) {
            this.$message.warning("关联资料设置是否允许下载");
            return;
          }
          if (element.lookstatus == undefined) {
            this.$message.warning("关联资料设置是否允许试看");
            return;
          }
        }
      }

      if (getChineseStrLength(this.postForm.name) > 80) {
        this.$message({
          message: "课程名称不能超过40个字",
          type: "warning"
        });
        return;
      }

      let countRate = 0;
      if (this.agentLevel == 0) {
        countRate =
          this.postForm.firstCommissionRate +
          this.postForm.secondCommissionRate +
          this.postForm.thirdCommissionRate;
      } else if (this.agentLevel == 1) {
        countRate =
          this.postForm.firstCommissionRate +
          this.postForm.secondCommissionRate +
          this.postForm.thirdCommissionRate +
          this.postForm.agentCommissionRate;
      } else if (this.agentLevel == 3) {
        countRate =
          this.postForm.firstCommissionRate +
          this.postForm.secondCommissionRate +
          this.postForm.thirdCommissionRate +
          this.postForm.agentCommissionRate +
          this.postForm.partnerCommissionRate +
          this.postForm.branchCommissionRate;
      }
      if (this.postForm.teacherId) {
        this.postForm.teacherCommissionRate = this.postForm
          .teacherCommissionRate
          ? parseFloat(this.postForm.teacherCommissionRate)
          : 0;
        countRate += this.postForm.teacherCommissionRate;
      }
      if (countRate > 100) {
        this.$message.warning("所有分成比例之和不能超出100%");
        return;
      }
      if (this.$route.query.columnId) {
        this.postForm.columnId = this.$route.query.columnId;
      }
      this.$refs.postForm.validate(valid => {
        if (valid) {
          if (this.btnLoading) {
            return;
          }
          this.btnLoading = true;
          if (this.isEdit) {
            this.handleUpdate();
          } else {
            this.handleCreate();
          }
        } else {
          this.postForm.columnId = 0;
          return false;
        }
      });
    },
    linkToCategory() {
      this.$router.push({ name: "courseCategory" });
    },
    linkToLecturer() {
      this.$router.push({ name: "lecturers" });
    },
    // // 图片裁剪
    // closeImageCropper() {
    //   this.imagecropperShow = false
    // },
    // cropSuccess(resData) {
    //   this.imagecropperShow = false
    //   this.imagecropperKey = this.imagecropperKey + 1
    //   this.postForm.courseAvatar = resData.data.imageUrl
    // },
    submitAvatarUpload() {
      this.$refs.avatarUpload.submit();
    },
    handleAvatarSuccess(response, file, fileList) {
      if (response.statusCode == 200) {
        this.postForm.courseAvatar = response.data.imageUrl;
        this.$message({
          message: "上传成功!",
          type: "success"
        });
      } else {
        this.$message.error("上传失败，请稍候再试!");
      }
    },
    handleBannerSuccess(response, file, fileList) {
      if (response.statusCode == 200) {
        this.postForm.banner.push({
          cbId: null,
          courseId: null,
          url: response.data.imageUrl,
          sort: null
        });
      } else {
        this.$message.error("上传失败，请稍候再试!");
      }
    },
    setDefultImg(e) {
      e.target.src = defultImg;
    },
    handleAvatarRemove(file, fileList) {
      this.postForm.courseAvatar = null;
    },
    submitPreviewUpload() {
      this.$refs.previewUpload.submit();
    },
    handlePreviewSuccess(response, file, fileList) {
      if (response.statusCode == 200) {
        this.postForm.forenoticeQrcodeBg = response.data.imageUrl;
        this.$message({
          message: "上传成功!",
          type: "success"
        });
      } else {
        this.$message.error("上传失败，请稍候再试!");
      }
    },
    handleRemove(file, fileList) {
      this.postForm.banner.splice(this.postForm.banner.indexOf(file), 1);
      var data = { imgUrl: file.url };
      delImg(data)
        .then(res => {
          // console.log(res)
        })
        .catch(err => {
          console.log(err);
        });
    },
    handleBeforeUpload(file) {
      console.log("上传文件之前触发啊、。。。");
      const isImg = file.type == "image/jpeg" || file.type == "image/png";
      if (!isImg) {
        this.$message.warning("上传图片只能是 JPG 或 PNG 格式");
      }
      const isLt3M = file.size / 1024 / 1024 < 3;
      if (!isLt3M) {
        this.$message.error("上传图片大小不能超过 3MB!");
      }
      return isImg && isLt3M;
    },
    //视频上传验证
    beforeVideoUpload(file) {
      const isVideo = file.type === "video/mp4";
      const isLt = file.size / 1024 / 1024 < 100;
      if (!isVideo) {
        this.$message.error("上传视频只能是 MP4 格式!");
      }
      if (!isLt) {
        this.$message.error("上传视频大小不能超过 100MB!");
      }
      return isVideo && isLt;
    },
    //视频上传成功
    handleVideoSuccess(res, file) {
      if (res.key) {
        this.postForm.courseVideo = this.baseUrl + res.key;
        this.$message({
          message: "上传成功!",
          type: "success"
        });
      } else {
        this.$message.error("上传失败，请稍候再试!");
      }
      this.videoFlag = false;
    },
    //视频上传进度
    uploadVideoProcess(event, file, fileLis) {
      this.videoFlag = true;
      this.videoUploadPercent = parseFloat(file.percentage.toFixed(1));
    },
    teacherSelect(val) {
      if (val == 1) {
        this.teacherShow = true;
      } else {
        this.teacherShow = false;
      }
    },
    syncSearchTeachers(query) {
      this.syncLoading = true;
      getMemberSearch(query)
        .then(res => {
          this.syncLoading = false;
          const resData = res.data.data;
          this.teacherList = [];
          for (let i = 0; i < resData.length; i++) {
            this.teacherList.push({
              userId: resData[i].userId,
              nickname:
                resData[i].nickname + `（ID: ${resData[i].encodeUserId}）`
            });
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    teacherOptionSelect(selectedOption, id) {
      this.postForm.teacherId = selectedOption.userId;
    },
    teacherOptionRemove(removedOption, id) {
      this.postForm.teacherId = null;
    },
    courseCommissionSelect(val) {
      if (val == 1) {
        this.courseCommissionShow = true;
      } else {
        this.courseCommissionShow = false;
      }
    },
    close() {
      this.$store.dispatch("delVisitedViews", this.$route).then(views => {
        const latestView = views.slice(-1)[0];
        if (this.$route.query.columnId) {
          const columnId = this.$route.query.columnId;
          this.$router.push({ path: `/columns/columnDetail/${columnId}` }); // latestView.path
        } else if (
          this.$route.params.columnId &&
          this.$route.params.columnId != -1
        ) {
          const columnId = this.$route.params.columnId;
          this.$router.push({ path: `/columns/columnDetail/${columnId}` }); // latestView.path
        } else {
          if (latestView) {
            const type = this.$route.params.courseType;
            this.$router.push({ name: type }); // latestView.path
          } else {
            this.$router.push("/");
          }
        }
      });
    },
    linkToCreate() {
      let type = "";
      switch (this.postForm.courseType) {
        case 0:
          type = "videos";
          break;
        case 1:
          type = "audios";
          break;
        case 2:
          type = "articles";
          break;
      }
      const liveAt = Date.parse(this.postForm.liveAt);
      const currentTime = Date.parse(new Date());
      const columnId = this.postForm.columnId;
      if (liveAt > currentTime) {
        type = "previews";
      }
      const encodeUserId = this.encodeUserId;
      this.$router.push({
        name: "createCourse",
        params: {
          courseType: type,
          postData: this.postForm,
          columnId: columnId,
          encodeUserId: encodeUserId
        }
      });
    },
    saveRelated() {},
    hideAddRelated(msg) {
      this.objData.push(...msg);
      this.isShowAddRelated = false;
    },
    addRelObj(relType, objData) {
      this.relType = relType;
      this.objData = objData;
      this.isShowAddRelated = true;
    },
    cancelRel(type, index) {
      if (type == 1) {
        this.postForm.datumArr.splice(index, 1);
        console.log(this.postForm.datumArr);
      } else if (type == 2) {
        this.postForm.socialArr.splice(index, 1);
      } else if (type == 3) {
        this.postForm.examArr.splice(index, 1);
      }
    }
  }
};
</script>
<style scoped>
.el-btn {
  color: #409eff;
  border: 1px solid #409eff;
}
.avatar-uploader-icon {
  width: 180px;
  height: 120px;
  line-height: 120px;
}
.avatar {
  width: 180px;
  height: 120px;
}
.preview-uploader {
  width: 180px;
  height: 360px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.preview-uploader:hover {
  border-color: #409eff;
}
.preview-uploader-icon {
  width: 180px;
  height: 360px;
  line-height: 360px;
}
.preview {
  width: 180px;
  height: 360px;
}
</style>
